package com.xuecheng.checkcode.domain.template;

import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.checkcode.domain.model.dto.CheckCodeGenerateDto;
import com.xuecheng.checkcode.domain.model.dto.CheckResult;
import com.xuecheng.checkcode.domain.model.enums.CheckResultEnum;
import com.xuecheng.checkcode.infrastructure.util.RandomUtil;

import java.util.Objects;


/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-09-07  18:23
 */
public abstract class AbstractCheckCodeTemplate {

    private static final String PREFIX = "checkcode-";

    public CheckCodeGenerateDto generate(Integer length){
        String key = getKey(PREFIX);
        String value = RandomUtil.getRandom(length);
        CheckCodeGenerateDto checkCodeGenerateDto = new CheckCodeGenerateDto(key, value);
        save(checkCodeGenerateDto);
        return checkCodeGenerateDto;
    }

    public abstract String getKey(String prefix);

    public abstract void save(CheckCodeGenerateDto checkCodeGenerateDto);

    public CheckResult check(String key, String myValue){
        // 检查是否禁用
        if (isBan(key)){
            return CheckResult.error(CheckResultEnum.BAN.getType());
        }
        String value = getValue(key);
        if (Objects.isNull(value)){
            return CheckResult.error(CheckResultEnum.EXPIRE.getType());
        }
        return value.equalsIgnoreCase(myValue) ? CheckResult.success() : CheckResult.error(CheckResultEnum.ERROR.getType());
    }

    public abstract String getValue(String key);

    public abstract String getErrorKey(String key);

    public abstract Boolean checkErrorTime(String key);

    public abstract void deleteKey(String key);

    public abstract Boolean isBan(String key);

    public abstract String getBanKey(String key);

}
